package com.virtual.rerijaapps.pet.ui;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.joda.time.LocalDate;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import be.billington.calendar.recurrencepicker.RecurrencePickerDialog;
import be.billington.calendar.recurrencepicker.RecurrencePickerDialog.OnRecurrenceSetListener;

import com.androidquery.AQuery;
import com.google.ical.compat.jodatime.LocalDateIterable;
import com.google.ical.compat.jodatime.LocalDateIteratorFactory;
import com.tripadvisor.seekbar.CircularClockSeekBar;
import com.tripadvisor.seekbar.CircularClockSeekBar.OnSeekBarChangeListener;
import com.virtual.rerijaapps.pet.PrincipalScreen;
import com.virtual.rerijaapps.pet.R;

public class ClockWidget extends RelativeLayout implements OnSeekBarChangeListener, OnRecurrenceSetListener
{

	private Context mContext;
	
	public AQuery mAquery;
	
	private String mLastHour;
	
	public ClockWidget( Context context )
	{
		super( context, null );
		mContext = context;
		init( context, null );
	}

	public ClockWidget( Context context, AttributeSet attrs )
	{
		super( context, attrs );
		init( context, attrs );
	}

	public ClockWidget( Context context, AttributeSet attrs, int defStyle )
	{
		super( context, attrs, defStyle );
		init( context, attrs );
	}
	
	public void init( Context context, AttributeSet attrs )
	{
		mContext = context;
		View rootView = View.inflate( mContext , R.layout.clock_widget, this );
		if ( !isInEditMode() )
		{
			mAquery = new AQuery( rootView );
			setClocks();
			mAquery.id( R.id.set_hour ).clicked( this, "clickSetHour" );
		}
	}

	private void setClocks()
	{
		( ( CircularClockSeekBar ) mAquery.id( R.id.calendar_view_hour ).getView() ).setSeekBarChangeListener( this );
		( ( CircularClockSeekBar ) mAquery.id( R.id.calendar_view_minute ).getView() ).setSeekBarChangeListener( this );
	}

	@Override
	public void onProgressChanged( CircularClockSeekBar seekBar, int progress, boolean fromUser ) 
	{
		if ( R.id.calendar_view_minute == seekBar.getId() )
		{
			mAquery.id( R.id.minute ).text( String.valueOf( ( progress * 60 ) / 120 ) );
		}
		else
		{
			String hour = String.valueOf( 0 == ( ( progress * 24 ) / 120 ) ? 00 : ( ( String.valueOf( ( progress * 24 ) / 120 ) ).length() < 2 ? "0" + ( ( progress * 24 ) / 120 ) : ( progress * 24 ) / 120 ) );
			mAquery.id( R.id.hour ).text( 24 != Integer.parseInt( hour ) ? ( !"0".equals( hour ) ? hour : "00" ) : "00" );
		}
	}

	@Override
	public void onStartTrackingTouch( CircularClockSeekBar seekBar ) 
	{
		
	}

	@Override
	public void onStopTrackingTouch( CircularClockSeekBar seekBar ) 
	{
		
	}

	@Override
	public void onAnimationComplete( CircularClockSeekBar seekBar )
	{
		
	}
	
	/**
	 * Evento que se genera al pulsar sobre establecer hora.
	 * 
	 * @param view - Vista que lo genera.
	 */
	public void clickSetHour( View view )
	{
		if ( mAquery.id( R.id.set_description ).getText() != null && !mAquery.id( R.id.set_description ).getText().toString().isEmpty() )
		{
			RecurrencePickerDialog recurrencePickerDialog = new RecurrencePickerDialog();
			recurrencePickerDialog.show( ( ( PrincipalScreen ) mContext ).getSupportFragmentManager(), "recurrencePicker" );
			recurrencePickerDialog.setOnRecurrenceSetListener( this );
			mLastHour = mAquery.id( R.id.hour ).getText().toString() + ":" + mAquery.id( R.id.minute ).getText();
			( ( PrincipalScreen ) mContext ).mNewEvent.mLastDialogClock.cancel();
			mAquery.id( R.id.set_description ).getEditText().setError( null );
		}
		else
		{
			mAquery.id( R.id.set_description ).getEditText().setError( mContext.getString( R.string.add_pet_tarea_description_desc ) );
		}
	}
	
	@Override
	public void onRecurrenceSet( String rrule ) 
	{
		( ( PrincipalScreen ) mContext ).showLoadingDialog( true );
		new RecurrenceToLayoutTask().execute( rrule );
	}
	
	private class RecurrenceToLayoutTask extends AsyncTask<String, Void, LocalDateIterable>
	{

		@Override
		protected LocalDateIterable doInBackground( String... paramsTask ) 
		{
			String rrule = paramsTask[0];
			LocalDateIterable dates = null;
			try
			{
				if ( !rrule.contains( "UNTIL" ) && !rrule.contains( "COUNT" ) )
				{
					GregorianCalendar calendarToTenYears = new GregorianCalendar();
					calendarToTenYears.set( Calendar.YEAR, calendarToTenYears.get( Calendar.YEAR ) + 1 );
					rrule += ";UNTIL=" + new SimpleDateFormat( "yyyy-MM-dd" ).format( calendarToTenYears.getTime() ).replace( "-", "" );
				}
				dates = LocalDateIteratorFactory.createLocalDateIterable( "RRULE:" + rrule, LocalDate.now(), true );
				Thread.sleep( 2000 );
			}
			catch( Exception ex )
			{
				ex.printStackTrace();
				return null;
			}
			
			return dates;
		}

		@Override
		protected void onPostExecute( LocalDateIterable result ) 
		{
			if ( null != result )
			{
				for ( LocalDate date : result ) 
			    {
					String generateDate = date.getDayOfMonth() + "/" + date.getMonthOfYear() + "/" + date.getYear();
					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, 80 );
					params.bottomMargin = 5;
					TareaWidget newTarea = new TareaWidget( mContext );
					newTarea.mDate = generateDate;
					newTarea.mDescription = mAquery.id( R.id.set_description ).getText().toString();
					newTarea.mHour = mLastHour;
					newTarea.setOnLongClickListener( ( ( PrincipalScreen ) mContext ).mNewEvent );
					newTarea.setLayoutParams( params );
					( ( LinearLayout ) ( ( PrincipalScreen ) mContext ).mNewEvent.mAquery.id( R.id.new_event_tareas_container ).getView() ).addView( newTarea );
					newTarea.setInfo();
			    }
			}
			else
			{
				
			}
			( ( PrincipalScreen ) mContext ).completeDialog();
			super.onPostExecute( result );
		}
		
		
		
	}
	
}
